import { useLocation, Navigate } from "react-router-dom";
import { AxiosCanceler } from "@/utils/http/axiosCancel";
import { searchRoute } from "@/utils/util";
import { store } from "@/redux/index";
import { PageEnum } from "@/enums/pageEnum";
// import { useEffect } from "react";
// import { setDictMapAction } from "@/redux/modules/dict/asyncAction";
import useDictCache from "@/caches/useDictCache";

const axiosCanceler = new AxiosCanceler();

/**
 * @description 路由守卫组件
 * */
const AuthRouter = (props: { children: JSX.Element }) => {
	const { user, permission } = store.getState();
	const { pathname } = useLocation();
	// user auth
	const token = user.accessToken;

	// * clean request before navigate
	axiosCanceler.removeAllPending();

	// match router
	const route = searchRoute(pathname, permission.backMenuList || []);
	const hasRoute = route && Object.keys(route).length > 0;

	const { setDictMap } = useDictCache();
	// set catch dict
	if (hasRoute && token) setDictMap();

	// * not need auth
	if (hasRoute && !route.meta?.requiresAuth) return props.children;

	// * judge auth (backMenu mode means "menu = auth", so not need this)
	if (!token) return <Navigate to={PageEnum.BASE_LOGIN} replace />;

	// *not match router
	if (!hasRoute) {
		return <Navigate to="/404" />;
	}

	// * normal return
	return props.children;
};

export default AuthRouter;
